package gr.handmademarket.bl.operations;

import gr.handmademarket.hibernate.HibernateUtil;
import gr.handmademarket.po.implementations.KeyGenerator;
import gr.handmademarket.po.implementations.Product;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * operation that saves a product.
 */
public class SaveProductOperation {

	/**
	 * fetching key value of categories.
	 */
	@SuppressWarnings("nls")
	private static final String hqlString = 
			"select kg from KeyGenerator kg where kg.tableName = :entityName";
	
	/**
	 * the product.
	 */
	private Product product;
	
	/**
	 * Creates a new CreateCategoryOperation object. 
	 *
	 */
	public SaveProductOperation() {
		// empty
	}
	
	/**
	 * execution method.
	 */
	@SuppressWarnings("nls")
	public void execute(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		if (product.getCode() == -1){
			storeProduct(session);
		} else {
			session.merge(product);
		}
        session.getTransaction().commit();
	}
	
	private void storeProduct(Session session){
		Query query = session.createQuery(hqlString);
		query.setString("entityName", "products");
		KeyGenerator keyGen = (KeyGenerator) query.list().get(0);
		Integer nextVal = keyGen.getKeyValue() + 1;
		product.setCode(nextVal);
		keyGen.setKeyValue(nextVal);
        session.save(product);
	    session.update(keyGen);
	}
	
	public void setProduct(Product product) {
		this.product = product;
	}
	
	public Product getProduct() {
		return product;
	}

}
